<!--
 * @Author: xuman
 * @Date: 2020-05-27 10:18:33
 * @LastEditors: xuman
 * @LastEditTime: 2020-06-10 15:46:31
-->
<template>
  <el-dialog
    title="特征映射"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :visible="true"
    width="70%"
    :before-close="handleClose"
    class="map"
  >
    <div class="map_search">
      <el-input
        type="text"
        size="mini"
        clearable
        placeholder="请输入参数CODE进行搜索"
        v-model.trim="columnName"
        @change="handleChangeColumn"
      />
      <el-button size="mini" type="primary" @click="handleAutoMap"
        >智能映射</el-button
      >
    </div>
    <el-table
      ref="multipleTable"
      :data="data"
      fit
      highlight-current-row
      :max-height="500"
      v-loading="loading"
    >
      <el-table-column
        label="参数CODE"
        min-width="130px"
        prop="columnName"
        align="center"
      />
      <el-table-column
        label="参数名"
        min-width="130px"
        prop="display"
        align="center"
      />
      <el-table-column
        label="类型"
        min-width="160px"
        prop="columnType"
        align="center"
      />
      <el-table-column label="映射特征" min-width="160px" align="center">
        <template slot-scope="scope">
          <el-select
            v-model.trim="scope.row.mappingFeature"
            :placeholder="`输入关键字筛选${scope.row.required ? '(必填)' : ''}`"
            filterable
            clearable
            remote
            :remote-method="name => handleSearchFeature(name, scope.$index)"
            @change="val => handleChangeFeature(val, scope.$index)"
            @visible-change="val => handleVisibleChange(val, scope.$index)"
            :loading="featureLoading"
            size="mini"
          >
            <el-option
              v-for="item in scope.row.featureOptions"
              :key="item.feature_code"
              :label="item.feature_desc"
              :value="item.feature_code"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="特征CODE"
        align="center"
        prop="featureCode"
        width="180px"
      />
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="page.page"
      :page-size="page.pageSize"
      layout="total, prev, pager, next"
      :total="page.total"
    >
    </el-pagination>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取消</el-button>
      <el-button size="mini" type="primary" @click="handleSure">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import * as Api from '@/api/risksystem/feature/model'
import { getFeatureListNoPage } from '@/api/risksystem/feature'
import { cloneDeep, debounce } from 'lodash'

interface IPage {
  page: number
  pageSize: number
  total: number
}

interface ITableData {
  id: number
  columnName: string
  columnType: string
  feature_code: string
  featureCode: string
  featureOptions?: any[]
  mappingFeature: string
}

@Component({})
export default class FeatureMap extends Vue {
  @Prop() getList!: Function
  @Prop() private modelCode!: string

  private data: ITableData[] = []
  private featureLoading: boolean = false
  private loading: boolean = false
  private columnName: string = ''
  private totalData: any = {}
  private selectFeatureList: string[] = []
  private featureOptions: any[] = []
  private page: IPage = {
    page: 0,
    pageSize: 10,
    total: 0
  }

  async created() {
    await this.getFeatureListNoPage()
    this.getModelInParam()
  }

  @Watch('data', { deep: true })
  private handleDataChange(val: ITableData[]) {
    const { page } = this.page
    this.$set(this.totalData, page, val)
  }

  // 获取特征
  private async getFeatureListNoPage(name?: string) {
    const {
      data: { list }
    } = await getFeatureListNoPage({ name })
    this.featureOptions = list
  }

  // 特征搜索
  private async handleSearchFeature(name: string, index: number) {
    if (name) {
      this.featureLoading = true
      const {
        data: { list }
      } = await getFeatureListNoPage({ name })
      const new_list = this.filterSelectFeature(list)
      this.$set(this.data[index], 'featureOptions', new_list)
      this.featureLoading = false
    } else {
      this.$set(this.data[index], 'featureOptions', [])
    }
  }

  private handleChangeFeature(val: string, index: number) {
    this.selectFeatureList[index] = val
    this.$set(this.data[index], 'featureCode', val)
    const featureOptions = this.data[index].featureOptions
    if (val && featureOptions && featureOptions.length) {
      featureOptions.forEach(item => {
        if (item.feature_code === val) {
          this.$set(this.data[index], 'mappingFeature', item.feature_desc)
        }
      })
    } else {
      this.$set(this.data[index], 'mappingFeature', '')
    }
  }

  // 过滤选中的特征code
  private filterSelectFeature(data: any[]) {
    return data.map((item: any) => {
      item.disabled = false
      if (this.selectFeatureList.includes(item.feature_code)) {
        item.disabled = true
      }
      return item
    })
  }

  // 下拉框状态
  private handleVisibleChange(val: boolean, index: number) {
    if (val) {
      const new_list = this.filterSelectFeature(this.featureOptions)
      this.$set(this.data[index], 'featureOptions', new_list)
    }
  }

  private handleChangeColumn(val: string) {
    this.columnName = val
    this.getModelInParam()
  }

  // 获取入参
  private async getModelInParam() {
    this.loading = true
    try {
      const {
        data: { records, current: page, total }
      } = await Api.getModelInParam({
        modelCode: this.modelCode,
        ...this.page,
        columnName: this.columnName
      })
      this.page = { ...this.page, page, total }
      records.forEach((item: any, index: number) => {
        item.featureOptions = this.featureOptions
        if (item.featureCode) {
          this.selectFeatureList[index] = item.featureCode
        }
      })
      this.data = records
    } finally {
      this.loading = false
    }
  }

  // 智能映射
  private handleAutoMap() {
    debounce(async () => {
      let isMap = false
      const data = cloneDeep(this.data)
      data.map((item, index) => {
        const featureObj = this.featureOptions.find(
          (val: any) => val.feature_code === item.columnName
        )
        if (featureObj) {
          isMap = true
          const { feature_code, feature_desc } = featureObj
          data[index].featureCode = feature_code
          data[index].mappingFeature = feature_desc
        }
      })
      this.data = data
      if (!isMap)
        this.$message.warning('未找到可智能匹配的字段，请手动进行映射操作!')
    }, 500)()
  }

  // 分页
  private handleCurrentChange(val: number) {
    this.page.page = val
    this.totalData.hasOwnProperty(val)
      ? (this.data = this.totalData[val])
      : this.getModelInParam()
  }
  private flatten(arr: any) {
    let arr1: any = []
    arr.forEach((val: any) => {
      if (Array.isArray(val)) {
        arr1 = arr1.concat(val)
      } else {
        arr1.push(val)
      }
    })
    return arr1
  }
  // 确定
  private handleSure() {
    debounce(async () => {
      const data = this.flatten(Object.values(this.totalData)).filter(
        (item: any) => item.mappingFeature
      )
      let arr: any = []
      data.forEach((item: any) => {
        item.featureOptions = []
        arr.push(item)
      })
      if (!arr.length) return this.$message.warning('请填写映射内容！')
      await Api.submitModelMap(arr)
      this.$message.success('映射成功！')
      this.handleClose()
      this.getList()
    }, 1000)()
  }

  // 关闭弹窗
  private handleClose() {
    this.$emit('handleClose')
  }
}
</script>
<style lang="scss" scoped>
.map {
  &_search {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding-bottom: 16px;
    .el-input {
      flex: 1;
      margin-right: 16px;
    }
  }
}
</style>
